package com.bwie.utils;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Component
public class EasyPoiUtil<T> {

    /**
     * 导入
     */
    /**
     * @param file：
     * @param pojoClass
     * @return
     * @throws Exception
     */
    public List<T> importFileExcel(MultipartFile file, Class<T> pojoClass) {
        List<T> list = null;
        try {
            //文件输入流
            InputStream inputStream = file.getInputStream();
            //创建一个导入参数对象
            ImportParams params = new ImportParams();
            //从第几行读取
            params.setHeadRows(1);
            list = ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    /**
     * 普通导出
     *
     * @param response
     */
    public <T> void exportExcel(HttpServletResponse response, List<T> list, Class<T> clazz, String fileName) {
        // 1.导出，并获取工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "简单导出测试表"), clazz, list);
        // 2.输出
        responseWorkbook(response, workbook, fileName);
    }

    private void responseWorkbook(HttpServletResponse response, Workbook workbook, String fileName) {
        try {
            response.setHeader("Content-disposition", "attachment;" + "filename*=utf-8''" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream; charset=UTF-8");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
